import cefsharpAdapter from '../cefsharp'

// === 监控相关处理函数 ===
export async function handleMonitorRequests(method, url, data, params) {
    // GET请求处理
    if (method === 'get') {

        // 获取硬件数量
        if (/\/monitor\/hardware\/count/.test(url)) {
            console.log('🔍 [API] CefSharp获取硬件数量:', params)
            return await cefsharpAdapter.callDbMethod('GetHardwareCount', params.deviceId)
        }

        // 读取变量
        if (/\/monitor\/variables\/read/.test(url)) {
            console.log('🔍 [API] CefSharp读取变量:', data)
            return await cefsharpAdapter.callNativeMethod('ReadRemoteMonitorVariant', data)
        }

        // 写入变量
        if (/\/monitor\/variables\/write/.test(url)) {
            console.log('🔍 [API] CefSharp写入变量:', data)
            return await cefsharpAdapter.callNativeMethod('WriteRemoteMonitorVariant', data)
        }

        // 获取LT645协议选项
        if (/\/monitor\/lt645\/options/.test(url)) {
            console.log('🔍 [API] CefSharp获取LT645协议选项数据:', params)
            if (params) {
                return await cefsharpAdapter.callNativeMethod('GetDlt645Items', params.ruleCategory)
            }
            return await cefsharpAdapter.callNativeMethod('GetDlt645Items')
        }

        // 获取端口挂载设备列表
        if (/\/monitor\/ports\/load-device-type/.test(url)) {
            console.log('🔍 [API] CefSharp获取端口挂载设备类型数据:', params)
            return await cefsharpAdapter.callNativeMethod('GetPortLoadDeviceType', params.updateMode)
        }

        // 获取桥接端口号选项
        if (/\/monitor\/ports\/bridge-port-options/.test(url)) {
            console.log('🔍 [API] CefSharp获取桥接端口号选项数据:', params)
            return await cefsharpAdapter.callDbMethod('GetBridgePortOptions')
        }

        // 获取变量寄存器类型选项
        if (/\/monitor\/variables\/registers\/type-options/.test(url)) {
            console.log('🔍 [API] CefSharp获取变量寄存器类型选项数据:', params)
            return await cefsharpAdapter.callNativeMethod('GetVarRegistersTypeOptions', params.portProtoType)
        }

        // 获取编码类型列表
        if (/\/monitor\/code-types$/.test(url)) {
            console.log('🔍 [API] CefSharp获取编码类型列表数据')
            return await cefsharpAdapter.callNativeMethod('GetVarHJ212CodeSheetList')
        }

        // 获取编码类型数据
        if (/\/monitor\/code-types\/[^/]+\/data/.test(url)) {
            const codeType = url.match(/\/monitor\/code-types\/([^/]+)\/data/)?.[1]
            console.log('🔍 [API] CefSharp获取编码类型数据:', codeType)
            return await cefsharpAdapter.callNativeMethod('GetVarHJ212CodeSheetContent', codeType)
        }

        if (/\/monitor\/ports/.test(url)) {
            console.log('🔍 [API] CefSharp获取所有监控端口:', params)
            // 安全地获取 group_device_id，如果没有则传递 null
            const groupDeviceId = params && params.group_device_id ? params.group_device_id : null
            return await cefsharpAdapter.callDbMethod('GetAllMonitorPorts', groupDeviceId)
        }
        if (/\/monitor\/devices/.test(url)) {
            console.log('🔍 [API] CefSharp获取所有监控设备:', params)
            // 安全地获取 port_id，如果没有则传递 null
            const portId = params && params.port_id ? params.port_id : null
            const data = await cefsharpAdapter.callDbMethod('GetAllMonitorDevices', portId)
            
            // 处理CefSharp返回的数据结构
            let processedData = data
            
            // 如果返回的是对象而不是数组，尝试提取数据数组
            if (data && typeof data === 'object' && !Array.isArray(data)) {
                console.log('🔍 [API] 检测到CefSharp返回对象格式，尝试提取数据数组')
                
                // 尝试常见的数据字段名
                const possibleDataFields = ['data', 'devices', 'list', 'items', 'result']
                for (const field of possibleDataFields) {
                    if (data[field] && Array.isArray(data[field])) {
                        console.log(`✅ [API] 从 ${field} 字段中提取到设备数组，数量: ${data[field].length}`)
                        processedData = data[field]
                        break
                    }
                }
                
                // 如果没有找到数据数组，但对象有code字段，可能是标准响应格式
                if (processedData === data && 'code' in data) {
                    console.log('🔍 [API] 检测到标准响应格式，直接返回原始数据')
                    return data
                }
            }
            
            // 如果数据中包含错误的groupDeviceId字段，进行数据清理
            if (Array.isArray(processedData) && processedData.length > 0 && 'groupDeviceId' in processedData[0]) {
                console.log('⚠️ [API] 检测到返回数据中包含错误的groupDeviceId字段，正在清理...')
                const cleanedData = processedData.map(device => {
                    // 创建一个不包含groupDeviceId的新对象
                    // eslint-disable-next-line no-unused-vars
                    const { groupDeviceId, ...cleanDevice } = device
                    return cleanDevice
                })
                console.log('✅ [API] 数据清理完成，已移除groupDeviceId字段')
                return cleanedData
            }
            
            return processedData
        }
        // 获取变量列表
        if (/\/monitor\/variables/.test(url)) {
            console.log('🔍 [API] CefSharp获取所有监控变量:', params)
            const device_id = params && params.device_id ? params.device_id : null
            return await cefsharpAdapter.callDbMethod('GetAllMonitorVariants', device_id)
        }
    }

    // POST/PUT/DELETE请求处理
    if (['post', 'put', 'delete'].includes(method)) {
        return await handleMonitorModifyRequests(method, url, data)
    }

    return null
}

// === 监控修改请求处理 ===
export async function handleMonitorModifyRequests(method, url, data) {
    console.log('🔍 [API] handleMonitorModifyRequests:', { method, url, data })
    
    // 端口相关操作
    if (/\/monitor\/ports/.test(url)) {
        console.log('✅ [API] 匹配到端口相关操作')
        return await handleMonitorPortRequests(method, url, data)
    }
    
    // 设备相关操作
    if (/\/monitor\/devices/.test(url)) {
        console.log('✅ [API] 匹配到设备相关操作')
        return await handleMonitorDeviceRequests(method, url, data)
    }
    
    // 变量相关操作
    if (/\/monitor\/variables/.test(url)) {
        console.log('✅ [API] 匹配到变量相关操作，转发到 handleMonitorVariableRequests')
        return await handleMonitorVariableRequests(method, url, data)
    }

    console.log('❌ [API] 没有匹配到任何操作类型')
    return null
}

// === 监控端口请求处理 ===
export async function handleMonitorPortRequests(method, url, data) {
    if (method === 'post' && /\/monitor\/ports$/.test(url)) {
        // 需要把数据转换为json字符串
        return await cefsharpAdapter.callDbMethod('AddMonitorPort', data)
    }
    if (method === 'put' && /\/monitor\/ports\/[^/]+$/.test(url)) {
        return await cefsharpAdapter.callDbMethod('UpdateMonitorPort', data)
    }
    if (method === 'delete' && /\/monitor\/ports\/[^/]+$/.test(url)) {
        const portId = url.split('/').pop()
        return await cefsharpAdapter.callDbMethod('DeleteMonitorPort', portId)
    }
    return null
}

// === 监控设备请求处理 ===
export async function handleMonitorDeviceRequests(method, url, data) {
    if (method === 'post' && /\/monitor\/devices$/.test(url)) {
        // 需要把数据转换为json字符串
        return await cefsharpAdapter.callDbMethod('AddMonitorDevice', data)
    }
    if (method === 'put' && /\/monitor\/devices\/[^/]+$/.test(url)) {
        return await cefsharpAdapter.callDbMethod('UpdateMonitorDevice', data)
    }
    if (method === 'delete' && /\/monitor\/devices\/[^/]+$/.test(url)) {
        const deviceId = url.split('/').pop()
        return await cefsharpAdapter.callDbMethod('DeleteMonitorDevice', deviceId)
    }
    return null
}

// === 监控变量请求处理 ===
export async function handleMonitorVariableRequests(method, url, data) {
    console.log('🔍 [API] handleMonitorVariableRequests:', { method, url, data })
    
    if (method === 'post' && /\/monitor\/variables$/.test(url)) {
        console.log('✅ [API] 匹配到添加变量操作')
        console.log('🔍 [API] CefSharp添加监控变量:', data)
        return await cefsharpAdapter.callDbMethod('AddMonitorVariant', data)
    }
    if (method === 'post' && /\/monitor\/variables\/batch$/.test(url)) {
        console.log('✅ [API] 匹配到批量添加变量操作')
        console.log('🔍 [API] CefSharp批量添加监控变量:', data)
        return await cefsharpAdapter.callDbMethod('AddMonitorVariantBatch', data)
    }
    if (method === 'put' && /\/monitor\/variables\/[^/]+$/.test(url)) {
        console.log('✅ [API] 匹配到更新变量操作')
        const variableId = url.split('/').pop()
        console.log('🔍 [API] CefSharp更新监控变量:', { variableId, data: data })
        return await cefsharpAdapter.callDbMethod('UpdateMonitorVariant', data)
    }
    if (method === 'delete' && /\/monitor\/variables\/[^/]+$/.test(url)) {
        console.log('✅ [API] 匹配到删除变量操作')
        const variableId = url.split('/').pop()
        return await cefsharpAdapter.callDbMethod('DeleteMonitorVariant', variableId)
    }
    
    console.log('❌ [API] 没有匹配到任何变量操作')
    return null
} 